import {
	getBaseUrl,
	getApiPrefix
} from "./env";
import {
	getAuthorization
} from "./store";

// 添加请求拦截器
export function addRequestInterceptor() {
	const DEFAULT_TIMEOUT = 10000;
	const baseUrl = getBaseUrl()
	const prefix = getApiPrefix();

	uni.addInterceptor('request', {
		invoke(args) {
			// request 触发前拼接 url
			args.url = baseUrl + prefix + args.url;
			args.withCredentials = true;
			args.timeout = args.timeout ? args.timeout : DEFAULT_TIMEOUT
			if (!args.header) {
				args.header = {}
			}
			let authorization = getAuthorization()
			if (authorization) {
				args.header['Authorization'] = "Bearer " + authorization;
			}
		},
		success(res) {
			console.log(res);
			if (res.statusCode === 200) {
				const {
					success,
					msg,
					data
				} = res.data
				if (!success) {
					uni.showToast({
						icon: "error",
						title: msg
					})
					return false;
				}
				res.data = data
				return true;
			} else if (res.statusCode === 401) {
				uni.redirectTo({
					url: "/pages/login/auto"
				})
			} else {
				uni.showToast({
					icon: 'error',
					title: '请求错误，status:' + resp.statusCode
				})
			}
			return false;
		},
		fail(err) {
			uni.showToast({
				icon: "error",
				title: "请求出错"
			})
			console.error('interceptor-fail', err)
		},
		complete(res) {}
	})
}

export function doPost(url, data, succ) {
	uni.request({
		url: url,
		method: "POST",
		data: data,
		header: {
			'Content-Type': 'application/json'
		},
		success: (res) => {
			succ(res)
		}
	})
}

export function doGet(url, data, succ) {
	uni.request({
		url: url,
		method: "GET",
		data: data,
		success: (res) => {
			succ(res)
		}
	})
}

export function request(obj) {
	uni.request(obj)
}